package com.lphj.datainterface.handle;

import com.lphj.datainterface.component.Config.ReadConfig;
import com.lphj.datainterface.component.Config.ReadOtherConfig;
import com.lphj.datainterface.entity.CumOrder;
import com.lphj.datainterface.entity.Customer;
import com.lphj.datainterface.service.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Component
public class CumOrderHandle {

    @Autowired
    ReadConfig readConfig;

    @Autowired
    CumOrderService cumOrderService;

    @Autowired
    CustomerService customerService;

    @Autowired
    CumOrderDtlHandle cumOrderDtlHandle;

    @Autowired
    CumOrderListService cumOrderListService;

    @Autowired
    OrderService orderService;

    @Autowired
    OrderDtlService orderDtlService;

    @Autowired
    CumDeliveryService cumDeliveryService;

    @Autowired
    CumDeliveryDtlService cumDeliveryDtlService;

    @Autowired
    ReadOtherConfig readOtherConfig;
    /**
     * 添加订单
     * @param sheet
     * @param sheet1
     * @return
     */
    @Transactional
    public String addCumOrder(Sheet sheet,Sheet sheet1) {
        String info = "";
        int count = 0;
        String paper = "";
        Map<String,Object> data = null;
        //获取首行标题
        List<String> firstRowTitle = new ArrayList<String>();
        Row firstRow = sheet.getRow(0);
        boolean isNotNull = true;
        int index = 0;

        if(sheet != null) {
            //获取首行标题
            while(isNotNull) {
                Cell cell = firstRow.getCell(index);
                if(cell != null) {
                    firstRowTitle.add(cell.getStringCellValue());
                } else {
                    isNotNull = false;
                }
                index ++;
            }
            //下单日期
            int xdrq = 0;
            //订单编号
            int ddh = 0;
            //商户ID
            int shid = 0;
            //出库日期
            int ckrq = 0;
            for(int j=0;j<firstRowTitle.size();j++) {
                if(firstRowTitle.get(j).equals(readConfig.getS0_xdrq())) {
                    xdrq = j;
                } else if(firstRowTitle.get(j).equals(readConfig.getS0_ddh())) {
                    ddh = j;
                } else if(firstRowTitle.get(j).equals(readConfig.getS0_shid())) {
                    shid = j;
                } else if(firstRowTitle.get(j).equals(readConfig.getS0_ckrq())) {
                    ckrq = j;
                }
            }
            //创建单元格
            Cell cell;
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                //读取第r行
                Row row = sheet.getRow(r);
                if (row == null) {
                    break;
                }
                //订单号
                String paperNO = "";

                //日期处理；所有日期根据导入时的日期写入
                SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                //订单创建时间
                cell = row.getCell(xdrq);
                if (cell != null) {
                    //生成ERP订单号
                    try {
                        cell.setCellType(CellType.STRING);
                        paperNO = OrderIdHandle.getOrderId(r + "",sDateFormat.parse(cell.getStringCellValue()));
                        paper = paperNO.substring(0,paperNO.length() - 4);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                //观麦系统订单号写到订单备注
                String note = "";
                cell = row.getCell(ddh);
                if(cell != null) {
                    cell.setCellType(CellType.STRING);
                    note = cell.getStringCellValue();
                }
                //判断观麦订单是否以存在
                String co1 = cumOrderService.getCumOrderByNote(note);
                if(co1 == null) {
                    //判断paperNO是否存在
                    CumOrder co = cumOrderService.getCumOrderByPaperNO(paperNO);
                    //判断ERP订单号是否存在，如果存在则加1
                    int id = r;
                    while(co != null) {
                        id ++;
                        try {
                            //重新获取下单日期
                            cell = row.getCell(xdrq);
                            cell.setCellType(CellType.STRING);
                            //重新生成ERP订单号
                            paperNO = OrderIdHandle.getOrderId(id + "",sDateFormat.parse(cell.getStringCellValue()));
                            //根据新生成的订单号重新查询是否有对应的订单
                            co = cumOrderService.getCumOrderByPaperNO(paperNO);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }

                    //创建数据对象
                    CumOrder cumOrder = new CumOrder();
                    cumOrder.setPaperNO(paperNO);
                    cumOrder.setNote(note);
                    cell = null;
                    //分公司编号
                    cumOrder.setStoreNo(readOtherConfig.getStoreNO());
                    //客户编码
                    cell = row.getCell(shid);
                    cell.setCellType(CellType.STRING);
                    if(cell != null) {
                        Customer tCustomer = customerService.getCustomer(cell.getStringCellValue());
                        if(tCustomer == null) {
                            System.out.println("S0" + cell.getStringCellValue());
                        } else {
                            cumOrder.setCumNO(tCustomer.getCumNO());
                        }
                    }
                    cell = null;
                    //设置订单为未审核 --0未审核 --100审核
                    cumOrder.setTag(100);
                    //设置订单为未生成送货单 0=否 1=是
                    cumOrder.setTag1(0);

                    try {
                        //订单创建时间
                        cell = row.getCell(xdrq);
                        cell.setCellType(CellType.STRING);
                        if (cell != null) {
                            cumOrder.setCreateDate(sDateFormat.parse(cell.getStringCellValue()));
                            cumOrder.setOrderDate(sDateFormat.parse(cell.getStringCellValue()));
                            cumOrder.setLastUpdateTime(sDateFormat.parse(cell.getStringCellValue()));
                        } else {
                            cumOrder.setCreateDate(new Date());
                            cumOrder.setOrderDate(new Date());
                            cumOrder.setLastUpdateTime(new Date());
                        }
                        cell = null;

                        //出库日期
                        cell = row.getCell(ckrq);
                        cell.setCellType(CellType.STRING);
                        if (cell != null) {
                            cumOrder.setDeliveryDate(sDateFormat.parse(cell.getStringCellValue()));
                        } else {
                            cumOrder.setDeliveryDate(new Date());
                        }
                        cell = null;
                    } catch (ParseException e) {
                        info = "日期异常，请删除多余的日期并重新导入！";
                        return info;
                        //e.printStackTrace();
                    }
                    //设置订单类型
                    cumOrder.setOrderType1("");

                    //打印次数
                    cumOrder.setPrintCount(0);

                    //添加商品 如果该商品不存在则直接回滚并返回商品在观麦上的商品编码
                    data = cumOrderDtlHandle.insertCumOrderDtl(sheet1, cumOrder.getNote(), cumOrder.getPaperNO(),
                            cumOrder.getCumNO(),cumOrder.getStoreNo(),cumOrder.getOrderDate(),cumOrder.getDeliveryDate());
                    if(data.get("error") == null) {
                        //订单菜品总数
                        int goodsCount = (int) data.get("success");
                        cumOrder.setGoodsCount(goodsCount);
                        //System.out.println(cumOrder.getPaperNO());
                        count += cumOrderService.addCumOrder(cumOrder);
                        //生成客户送货单
                        cumDeliveryService.callST_CumDeliveryImport(cumOrder.getPaperNO(),"nmbt");
                        //客户送货单明细数量确认
                        cumDeliveryDtlService.changeOutQty(cumOrder.getPaperNO());
                        //客户送货单金额确认
                        cumDeliveryService.changeAmt(cumOrder.getPaperNO());
                        //生成采购订单
                        cumOrderListService.callTL_GenerationOrder("nmbt");
                        //修改订单状态tOrder
                        orderService.changeTag(paper + "%");
                        //修改订单出货数量tOrderDtl
                        orderDtlService.changeAcptQty(paper + "%",readOtherConfig.getStoreNO());
                    } else {
                        //返回商品为空的信息 由用户手动添加到ERP
                        return data.get("error").toString();
                    }
                }
            }

            if(data != null) {
                if(data.size() >= 1) {
                    info = "成功导入" + count + "条数据";
                } else {
                    info = "成功导入" + count + "条数据\n";
                    System.out.println("data is not null");
                }
            } else {
                info = "成功导入" + count + "条数据\n";
            }

        }
        return info;
    }
}
